<template>
  <div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ hasChildren: 'hasChildren', children: 'children', indent: 0 }"
    >
      <el-table-column prop="date" label="Date" sortable>
        <template #default="scope">
          <div style="display: flex; align-items: center; cursor: pointer" @click="handleExpand(scope.row)" v-if="scope.row.children">
            <span class="expand-text">{{ expandedRows.includes(scope.row.id) ? '收起' : '展开' }}</span>
            <span style="margin-left: 8px">{{ scope.row.date }}</span>
          </div>
          <span v-else>{{ scope.row.date }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="Name" sortable />
      <el-table-column prop="address" label="Address" sortable />
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { CaretRight } from '@element-plus/icons-vue'
import type { ElTable } from 'element-plus'

interface User {
  id: number
  date: string
  name: string
  address: string
  hasChildren?: boolean
  children?: User[]
}

// 跟踪展开的行
const expandedRows = ref<number[]>([]);

const tableRef = ref<InstanceType<typeof ElTable>>()

const handleExpand = (row: User) => {
  if (!row.children) return;
  const index = expandedRows.value.indexOf(row.id);
  if (index > -1) {
    expandedRows.value.splice(index, 1);
  } else {
    expandedRows.value.push(row.id);
  }
  // 使用 toggleRowExpansion 控制行的展开/收起
  tableRef.value?.toggleRowExpansion(row)
}

const tableData: User[] = [
  {
    id: 1,
    date: '2016-05-02',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 2,
    date: '2016-05-04',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
  {
    id: 3,
    date: '2016-05-01',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
    children: [
      {
        id: 31,
        date: '2016-05-01',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
      },
      {
        id: 32,
        date: '2016-05-01',
        name: 'wangxiaohu',
        address: 'No. 189, Grove St, Los Angeles',
      },
    ],
  },
  {
    id: 4,
    date: '2016-05-03',
    name: 'wangxiaohu',
    address: 'No. 189, Grove St, Los Angeles',
  },
]
</script>

<style scoped>
.expand-icon {
  transition: transform 0.2s;
  margin-right: 4px;
}
.expand-icon.is-expanded {
  transform: rotate(90deg);
}
.expand-text {
  color: #409EFF;
  font-size: 14px;
  margin-right: 8px;
}

/* 隐藏默认的展开图标 */
:deep(.el-table__expand-icon) {
  display: none !important;
}

/* 移除默认的缩进空间 */
:deep(.el-table__row--level-1) {
  padding-left: 0 !important;
}
</style>